package com.xxja.order.order.contoller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xxja.order.order.pojo.Order;
import com.xxja.order.order.service.OrderService;
import com.xxja.order.utils.PageRequest;
import com.xxja.order.utils.ResponseBuilder;
import com.xxja.order.utils.exception.ExceptionCast;
import com.xxja.order.utils.exception.ExceptionCode;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("order")
@Api("订单服务接口")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     * @param order
     * @return
     */
    @PostMapping
    public ResponseEntity<Long> createOrder(@RequestBody @Valid Order order) {
        Long id = this.orderService.createOrder(order);
        return ResponseBuilder.responseEntity(id, 201);
    }

    /**
     * 查询订单
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ResponseEntity<Order> queryOrderById(@PathVariable Long id) {
        Order order = this.orderService.queryById(id);
        if (order == null) {
            ExceptionCast.cast(ExceptionCode.ORDER_NOT_FOUND);
        }
        return ResponseBuilder.okEntity(order);
    }

    /**
     * 查询全部订单
     * @param pageRequest
     * @return
     */
    @GetMapping("list")
    public ResponseEntity<IPage<Order>> queryUserOrderList(PageRequest pageRequest) {
        IPage<Order> result = this.orderService.queryUserOrderList(pageRequest.setLimit());
        if (result == null) {
            ExceptionCast.cast(ExceptionCode.ORDER_USER_NOTFOUND);
        }
        return ResponseBuilder.responseIpage(result, 200);
    }

    /**
     * 更改订单状态
     * @param id
     * @param status
     * @return
     */
    @PutMapping("{id}/{status}")
    public ResponseEntity<Boolean> updateStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        Boolean boo = this.orderService.updateStatus(id, status);
        if (boo == null) {
            ExceptionCast.cast(ExceptionCode.ORDER_UPDATE_STATUS);
        }
        // 返回204
        return ResponseBuilder.allStatus(204);
    }

}
